package com.hp.gxw.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hp.gxw.cache.CommonCache;
import com.hp.gxw.constant.BaseEntry;
import com.hp.gxw.constant.LayTableR;
import com.hp.gxw.constant.R;
import com.hp.gxw.entity.BaseCommonDataDictionaryAndSet;
import com.hp.gxw.entity.CostEquipment;
import com.hp.gxw.entity.CostEquipmentLease;
import com.hp.gxw.service.ICostEquipmentLeaseService;
import com.hp.gxw.service.ICostEquipmentService;
import com.hp.gxw.utils.ConditionUtil;
import com.hp.gxw.utils.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huangping
 * @since 2024-01-04
 */
@RestController
@RequestMapping("/manage/equipment_lease")
public class CostEquipmentLeaseController extends CommonController{

    @Autowired
    private ICostEquipmentService iCostEquipmentService;

    @Autowired
    private ICostEquipmentLeaseService iCostEquipmentLeaseService;

    @Autowired
    public CommonCache commonCache;

    @PostMapping("/list/{happenMonth}")
    public LayTableR list(@PathVariable("happenMonth") String happenMonth, Integer page, Integer limit, String master) throws Exception {
        /**初始化发生月数据*/
        List<CostEquipment> elementsList = iCostEquipmentService.leaseListInfo(happenMonth);
        List<CostEquipmentLease> list = new ArrayList<>();
        for (CostEquipment costEquipment : elementsList) {
            if(costEquipment.getMonthLeaseAmount() == null){
                CostEquipmentLease costEquipmentLease = new CostEquipmentLease();
                costEquipmentLease.setEquipmentId(costEquipment.getId());
                costEquipmentLease.setLeaseAmount(costEquipment.getLeaseAmount()==null?BigDecimal.ZERO:costEquipment.getLeaseAmount().divide(costEquipment.getLeaseYear().multiply(new BigDecimal(12)),2,BigDecimal.ROUND_HALF_UP));
                costEquipmentLease.setDisable(false);
                costEquipmentLease.setHappenMonth(happenMonth);
                costEquipmentLease.setCreateUser(ShiroUtil.getUserId());
                costEquipmentLease.setCreateTime(new Date());
                list.add(costEquipmentLease);
            }
        }
        if(list.size() > 0){
            iCostEquipmentLeaseService.saveBatch(list);
        }

        QueryWrapper<Object> ew = ConditionUtil.convert(master, new QueryWrapper<>());
        ew.eq("happen_month", happenMonth);
        BaseEntry baseEntry = commonCache.init("cost_equipment_lease");
        IService<Object> iService = baseEntry.getIService();
        Page<Object> pageList = iService.page(new Page<>(page, limit), ew);
        List<BaseCommonDataDictionaryAndSet> collect = baseEntry.getSetList().stream().filter(e -> e.getQueryConstantId() != null).collect(Collectors.toList());
        List<Map> resultList = dataTransfer(pageList.getRecords(), collect);
        return LayTableR.result(0, pageList.getTotal(), resultList);
    }

    @PostMapping("/save")
    @ResponseBody
    public R save(@RequestBody List<CostEquipmentLease> list) {
        try {
            for (CostEquipmentLease costEquipmentLease : list) {
                costEquipmentLease.setCreateUser(ShiroUtil.getUserId());
                costEquipmentLease.setCreateTime(new Date());
            }
            iCostEquipmentLeaseService.updateBatchById(list);
        } catch (Exception e) {
            return R.error("系统异常");
        }
        return R.ok();
    }

    /**
     * 设备折旧导入
     * @param data
     * @return
     */
    @RequestMapping("/upload/{type}/{month}")
    @ResponseBody
    public R upload(String data, @PathVariable("type") String type, @PathVariable("month") String month) {
        if(StringUtils.isEmpty(month)){
            return R.error("参数异常");
        }
        String msg = "";
        try {
            List<Map> list = JSON.parseArray(data, Map.class);
            int rowNum = 1;
            List<CostEquipmentLease> saveList = new ArrayList<>();
            for (Map map : list) {
                if(map.get("number")==null || StringUtils.isEmpty(map.get("number").toString())){
                    continue;
                }
                CostEquipmentLease equipmentLease = new CostEquipmentLease();
                /**为空判断*/
                if (map.get("equipmentName")==null || StringUtils.isEmpty(map.get("equipmentName").toString())) {
                    msg += "第" + rowNum + "行数据,设备名称为空<br/>";
                }
                if (map.get("factoryNumber")==null || StringUtils.isEmpty(map.get("factoryNumber").toString())) {
                    msg += "第" + rowNum + "行数据,出厂编号为空<br/>";
                }
                if (map.get("amount")==null || StringUtils.isEmpty(map.get("amount").toString())) {
                    msg += "第" + rowNum + "行数据,租赁费用为空<br/>";
                    continue;
                }else{
                    try {
                        equipmentLease.setLeaseAmount(new BigDecimal(map.get("amount").toString()));
                    }catch (NumberFormatException ne) {
                        ne.printStackTrace();
                        msg += "第" + rowNum + "行数据,租赁费用只能是数字<br/>";
                    }
                }
                CostEquipment equipment = iCostEquipmentService.getOne(new LambdaQueryWrapper<CostEquipment>().eq(CostEquipment::getFactoryNumber, map.get("factoryNumber").toString()));
                if(equipment == null) {
                    msg += "第" + rowNum + "行数据,出厂编号："+map.get("factoryNumber").toString()+"的设备在设备档案中不存在!<br/>";
                    continue;
                }
                equipmentLease.setEquipmentId(equipment.getId());
                equipmentLease.setHappenMonth(month);
                equipmentLease.setDisable(false);
                equipmentLease.setCreateUser(ShiroUtil.getUserId());
                equipmentLease.setCreateTime(new Date());
                saveList.add(equipmentLease);
                rowNum++;
            }
            Map<Long, List<CostEquipmentLease>> collect = saveList.stream().collect(groupingBy(CostEquipmentLease::getEquipmentId));
            Set<Map.Entry<Long, List<CostEquipmentLease>>> entries = collect.entrySet();
            for (Map.Entry<Long, List<CostEquipmentLease>> entry : entries) {
                if(entry.getValue().size() > 1){
                    msg += "设备："+entry.getKey()+"存在多条数据!<br/>";
                }
            }
            if(StringUtils.isNotEmpty(msg)) {
                return R.error(msg);
            }
            if(list.size() > 0){
                switch (type){
                    case "cover":
                        iCostEquipmentLeaseService.coverUpload(saveList,month);
                        break;
                    case "difference":
                        Iterator<CostEquipmentLease> iterator = saveList.iterator();
                        while (iterator.hasNext()){
                            CostEquipmentLease equipmentLease = iterator.next();
                            CostEquipmentLease lease = iCostEquipmentLeaseService.getOne(new LambdaQueryWrapper<CostEquipmentLease>()
                                    .eq(CostEquipmentLease::getEquipmentId, equipmentLease.getEquipmentId())
                                    .eq(CostEquipmentLease::getHappenMonth, equipmentLease.getHappenMonth()));
                            if(lease != null){
                                iterator.remove();
                            }
                        }
                        if(list.size() > 0){
                            iCostEquipmentLeaseService.saveBatch(saveList);
                        }
                        break;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            return R.error("系统异常");
        }
        return R.ok();
    }
}

